﻿using UnityEngine;
using System.Collections;

public class CameraFollow : MonoBehaviour 
{
	public float xMargin = 1f; //distance in the x axis the player can move before the camera follows.
	public float yMargin = 1f; //distance in the y axis the player can move before the camera follows.
	public float xSmooth = 8f; //how smoothly the camera catches up with it's target movement in the x axis.
	public float ySmooth = 8f; //how smoothly the camera catches up with it's target movement in the y axis.
	public Vector2 maxXAndY;   //the maxinum x and y coordinates the camera can have.
	public Vector2 minXAndY;   //the minnum x and y coordinates the camera can have.

	private Transform player;  //reference to the player's transform

	void Awake()
	{
		//setting up the reference.
		player = GameObject.FindGameObjectWithTag("Player").transform;
	}

	bool CheckXMargin()
	{
		//returns true if the distance between the camera and the player in the x axis is greater than the x margin.
		return Mathf.Abs(transform.position.x - player.position.x) > xMargin;
	}

	bool CheckYMargin()
	{
		//returns true if the distance between the camera and the player in the y axis is greater than the y margin.
		return Mathf.Abs(transform.position.y - player.position.y) > yMargin;
	}

	void FixedUpdate()
	{
		TrackPlayer ();
	}

	void TrackPlayer()
	{
		//by default the target x and y coordinates of the camera are it's current x and y coordinates.
		float targetX = transform.position.x;
//		float targetY = transform.position.y;

		//if the player has moved beyond the x margoin...
		if(CheckXMargin())
			//...the target x coordinate should be a lerp between the camera's current x position and the player's current x position
			targetX = Mathf.Lerp(transform.position.x, player.position.x, xSmooth * Time.deltaTime);

		//if the player has moved beyond the y margoin...
//		if(CheckYMargin())
//			//...the target Y coordinate should be a lerp between the camera's current Y position and the player's current Y position
//			targetY = Mathf.Lerp(transform.position.y, player.position.y, ySmooth * Time.deltaTime);
//
//		//the target x and y coordinates should not be larger than the maxinum or smaller than the minnum.
//		targetX = Mathf.Clamp(targetX, minXAndY.x, maxXAndY.x);
//		targetY = Mathf.Clamp(targetY, minXAndY.y, maxXAndY.y);

		//set the camera's position to the target position with the same z component.
//		transform.position = new Vector3(targetX, targetY, transform.position.z);
		transform.position = new Vector3(targetX, transform.position.y, transform.position.z);
	}
}
